package com.bytedance.retrofit2.mime;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public final class FormUrlEncodedTypedOutput implements TypedOutput {
    private ByteArrayOutputStream content = new ByteArrayOutputStream();

    public final String mimeType() {
        return "application/x-www-form-urlencoded; charset=UTF-8";
    }

    public final void writeTo(OutputStream out) throws IOException {
        out.write(this.content.toByteArray());
    }

    public final void addField(String name, String value) {
        this.addField(name, true, value, true);
    }

    public final void addField(String name, boolean encodeName, String value, boolean encodeValue) {
        if (name == null) {
            throw new NullPointerException("name");
        }

        if (value == null) {
            throw new NullPointerException("value");
        }

        if (this.content.size() > 0) {
            this.content.write(38);
        }

        if (encodeName) {
            try {
                name = URLEncoder.encode(name, "UTF-8");
            } catch (IOException v0) {
                throw new RuntimeException(v0);
            }
        }

        try {
            if (encodeValue) {
                value = URLEncoder.encode(value, "UTF-8");
            }

            this.content.write(name.getBytes("UTF-8"));
            this.content.write(61);
            this.content.write(value.getBytes("UTF-8"));
            return;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public final long length() {
        return ((long) this.content.size());
    }

    public final String fileName() {
        return null;
    }
}

